﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using ZSZ.CommonMvc;
using ZSZ.Iservice;

namespace ZSZ.AdminWeb.App_Start
{
    public class HasPermissionIAuthorizationFilter : IAuthorizationFilter
    {
        IAdminUserService AdminUserService  = DependencyResolver.Current.GetService<IAdminUserService>();
        public void OnAuthorization(AuthorizationContext filterContext)
        {
            CheckPermissionAttribute[] checks = (CheckPermissionAttribute[])filterContext.ActionDescriptor.GetCustomAttributes(typeof(CheckPermissionAttribute),false);
            if (checks.Length<1)
            {
                return;
            }
            long? adminUserId = (long?)filterContext.HttpContext.Session["adminUserId"];
            if (adminUserId == null)
            {
                RedirectResult redis = new RedirectResult("/Main/Login");
                filterContext.Result = redis;
                return;
            }
            foreach (var item in checks)
            {
                if (AdminUserService.HasPermission((long)adminUserId.Value,item.PermissionName))
                {
                    continue;
                }
                if (filterContext.HttpContext.Request.IsAjaxRequest())
                {
                    JsonNetResult result = new JsonNetResult();
                    result.Data = new JsonCommon { Status = "err", ErrorMsg = "您没有权限" };
                    filterContext.Result = result;
                    return;
                }
                filterContext.Result = new ContentResult() { Content="您没有权限"};
            }
        }
    }
}